<?php

namespace App\V3\V3_2_7\Services;

use App\Services\CommonService;
use App\V3\V3_2_7\Models\AdminModel;
use App\V3\V3_2_7\Models\CustomTagModel;
use App\V3\V3_2_7\Models\LocationAnimalModel;
use App\V3\V3_2_7\Models\LocationLogModel;
use App\V3\V3_2_7\Models\MaterielProductContentModel;
use App\V3\V3_2_7\Models\OutAnimalTagModel;
use App\V3\V3_2_7\Models\ShelfLocationTagModel;
use App\V3\V3_2_7\Models\StorageManageModel;
use App\V3\V3_2_7\Models\StorageModel;
use App\V3\V3_2_7\Models\StorageShelfLocationModel;
use App\V3\V3_2_7\Models\StorageShelfModel;
use Illuminate\Http\JsonResponse;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class StorageShelfLocationService
{
    public static function list(array $data, array $condition, array $storageIdArr)
    {
        if (!empty($data['keyword'])) {
            return self::searchList($data, $condition, $storageIdArr);
        }
        $list = StorageModel::query()
            ->select(
                'a.id',
                'a.id as storage_id',
                'storage_name',
                'storage_address',
                'a.remarks',
                'username',
                'nickname',
                'user_id',
                'multi_user_id',
            )->from('storage as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->with(['shelfList' => function ($query) {
                $query->select(
                    'id',
                    'sort',
                    'remark',
                    'shelf_name',
                    'storage_id',
                    'shelf_type',
                    'id as shelf_id',
                    'is_product_shelf',
                )->with('locationList', function ($query) {
                    $query->select(
                        'sort',
                        'remark',
                        'shelf_id',
                        'location_name',
                        'location_type',
                        'id as location_id',
                        'is_product_shelf_location',
                        'standard_num as location_standard_num',
                    )->where('status', 1)->orderBy('sort', 'asc')
                        ->orderBy('location_type', 'asc');
                })->where('status', 1)->orderBy('sort', 'asc')
                    ->orderBy('shelf_type', 'asc');
            }])->where(function ($query) use ($condition, $storageIdArr) {
                $query->where('a.delete_flag', 0);
                if (!empty($condition)) {
                    $query->where($condition);
                } else {
                    $query->whereIn('a.id', $storageIdArr);
                }
            })->orderBy('a.created_at', 'desc')
            ->paginate($data['pageSize'], ['*'], '', $data['currentPage'])->toArray();

        if (!empty($list['data'])) {
            foreach ($list['data'] as &$val) {
                $val['staff_list'] = [];
                if (!empty($val['multi_user_id'])) {
                    $userIds = array_filter(explode(
                        ',',
                        $val['multi_user_id']),
                        function ($v) {
                            return $v !== '';
                        });
                    $userList = AdminModel::select(
                        'id',
                        'nickname',
                        'username',
                        'position',
                        'mobile'
                    )->whereIn('id', $userIds)->get();
                    if (!empty($userList)) {
                        $userList = $userList->toArray();
                        foreach ($userList as &$uVal) {
                            $uVal['storage_name'] = $val['storage_name'];
                        }
                    }
                    $val['staff_list'] = !empty($userList) ? $userList : [];
                }
                if (!empty($val['shelf_list'])) {
                    foreach ($val['shelf_list'] as &$sVal) {
                        $sVal['shelf_storage_num'] = 0;
                        $sVal['shelf_standard_num'] = 0;
                        if (!empty($sVal['location_list'])) {
                            foreach ($sVal['location_list'] as &$lVal) {
                                $sVal['shelf_standard_num'] += $lVal['location_standard_num'];
                                $lVal['location_storage_num'] = StorageManageModel::query()
                                    ->where([
                                        'delete_flag' => 0,
                                        ['in_storage_num', '>', 0],
                                        'shelf_id' => $sVal['shelf_id'],
                                        'location_id' => $lVal['location_id'],
                                        'storage_id' => $sVal['storage_id'],
                                    ])->sum('in_storage_num');
                                $sVal['shelf_storage_num'] += $lVal['location_storage_num'];
                            }
                        }
                    }
                }
            }
        }
        return $list;
    }

    private static function searchList(array $data, array $condition, array $storageIdArr)
    {
        $storageInfo = StorageModel::query()
            ->select(
                'id as storage_id',
            )
            ->where(function ($query) use ($data, $condition, $storageIdArr) {
                if (!empty($condition)) {
                    $query->where($condition);
                } else {
                    $query->whereIn('id', $storageIdArr);
                }
                $query->where('delete_flag', 0);
                $query->where('storage_name', 'like', '%' . $data['keyword'] . '%');
            })->get()->toArray();

        $shelfInfo = StorageShelfModel::query()
            ->select(
                'storage_id',
                'id as shelf_id',
            )->where(function ($query) use ($data, $condition, $storageIdArr) {
                if (!empty($condition)) {
                    $query->where('main_id', $data['main_id']);
                } else {
                    $query->whereIn('storage_id', $storageIdArr);
                }
                $query->where('status', 1);
                $query->where('shelf_name', 'like', '%' . $data['keyword'] . '%');
            })->get()->toArray();

        $locInfo = StorageShelfLocationModel::query()
            ->select(
                'shelf_id',
                'storage_id',
                'id as location_id',
            )->where(function ($query) use ($data, $condition, $storageIdArr) {
                if (!empty($condition)) {
                    $query->where('main_id', $data['main_id']);
                } else {
                    $query->whereIn('storage_id', $storageIdArr);
                }
                $query->where('status', 1);
                $query->where('location_name', 'like', '%' . $data['keyword'] . '%');
            })->get()->toArray();
        $list = [];
        $storInfo = array_merge($storageInfo, $shelfInfo, $locInfo);
        if (!empty($storInfo)) {
            foreach ($storInfo as $value) {
                $query = StorageModel::query()
                    ->select(
                        'a.id',
                        'a.id as storage_id',
                        'storage_name',
                        'storage_address',
                        'a.remarks',
                        'username',
                        'nickname',
                        'user_id',
                        'multi_user_id',
                    )->from('storage as a')
                    ->leftJoin('admin as b', 'b.id', '=', 'a.user_id');
                if (!empty($value['storage_id']) && !empty($value['shelf_id']) && empty($value['location_id'])) {
                    $query->with(['shelfList' => function ($query) use ($value) {
                        $query->select(
                            'id',
                            'sort',
                            'remark',
                            'shelf_name',
                            'storage_id',
                            'shelf_type',
                            'id as shelf_id',
                            'is_product_shelf',
                        )->where('status', 1)
                            ->where('id', $value['shelf_id'])
                            ->orderBy('sort', 'asc')
                            ->orderBy('shelf_type', 'asc');
                    }]);
                }
                if (!empty($value['storage_id']) && !empty($value['shelf_id']) && !empty($value['location_id'])) {
                    $query->with(['shelfList' => function ($query) use ($value) {
                        $query->select(
                            'id',
                            'sort',
                            'remark',
                            'shelf_name',
                            'storage_id',
                            'shelf_type',
                            'id as shelf_id',
                            'is_product_shelf',
                        )->with('locationList', function ($query) use ($value) {
                            $query->select(
                                'sort',
                                'remark',
                                'shelf_id',
                                'location_name',
                                'location_type',
                                'id as location_id',
                                'is_product_shelf_location',
                                'standard_num as location_standard_num',
                            )->where('status', 1)
                                ->where('id', $value['location_id'])
                                ->orderBy('sort', 'asc')
                                ->orderBy('location_type', 'asc');
                        })->where('id', $value['shelf_id'])
                            ->where('status', 1)->orderBy('sort', 'asc')
                            ->orderBy('shelf_type', 'asc');
                    }]);
                }
                $info = $query->where('a.id', $value['storage_id'])
                    ->first();
                if (!empty($info)) {
                    $info = $info->toArray();
                    if (!isset($info['shelf_list'])) $info['shelf_list'] = [];
                    if (!empty($info['shelf_list'])) {
                        foreach ($info['shelf_list'] as &$sVal) {
                            if (!isset($sVal['location_list'])) $sVal['location_list'] = [];
                        }
                    }
                    $info['staff_list'] = [];
                    if (!empty($info['multi_user_id'])) {
                        $userIds = array_filter(explode(
                            ',',
                            $info['multi_user_id']),
                            function ($v) {
                                return $v !== '';
                            });
                        $userList = AdminModel::select(
                            'id',
                            'nickname',
                            'username',
                            'position',
                            'mobile'
                        )->whereIn('id', $userIds)->get();
                        if (!empty($userList)) {
                            $userList = $userList->toArray();
                            foreach ($userList as &$uVal) {
                                $uVal['storage_name'] = $info['storage_name'];
                            }
                        }
                        $info['staff_list'] = !empty($userList) ? $userList : [];
                    }
                    if (!empty($info['shelf_list'])) {
                        foreach ($info['shelf_list'] as &$sVal) {
                            $sVal['shelf_storage_num'] = 0;
                            $sVal['shelf_standard_num'] = 0;
                            if (!empty($sVal['location_list'])) {
                                foreach ($sVal['location_list'] as &$lVal) {
                                    $sVal['shelf_standard_num'] += $lVal['location_standard_num'];
                                    $lVal['location_storage_num'] = StorageManageModel::query()
                                        ->where([
                                            'delete_flag' => 0,
                                            ['in_storage_num', '>', 0],
                                            'shelf_id' => $sVal['shelf_id'],
                                            'location_id' => $lVal['location_id'],
                                            'storage_id' => $sVal['storage_id'],
                                        ])->sum('in_storage_num');
                                    $sVal['shelf_storage_num'] += $lVal['location_storage_num'];
                                }
                            }
                        }
                    }
                }
                $list[] = $info;
            }
        }
        $nextUrl = "";
        $prevUrl = "";
        $currentPage = $data['currentPage'];
        $result = array_slice(array_values($list), --$data['currentPage'] * $data['pageSize'], $data['pageSize']);
        if (count($result) >= $data['pageSize']) {
            $nextUrl = $data['host'] . "v3.2.7/api/stor_shelf_location_list?=" . ($data['currentPage'] + 1);
        }
        if ($currentPage !== 1) {
            $prevUrl = $data['host'] . "v3.2.7/api/stor_shelf_location_list?=" . ($currentPage - 1);
        }
        return [
            'total' => count($list),
            'current_page' => $currentPage,
            'next_page_url' => $nextUrl,
            'prev_page_url' => $prevUrl,
            "path" => $data['host'] . "v3.2.7/api/statement_sell",
            "to" => $currentPage * $data['pageSize'],
            'data' => array_values($result),
            "per_page" => $data['pageSize']
        ];
        return $list;
    }

    public static function newList(array $data, array $condition, array $storageIdArr)
    {
        $list = StorageModel::query()
            ->select(
                'a.id',
                'a.id as storage_id',
                'storage_name',
                'storage_address',
                'a.remarks',
                'username',
                'nickname',
                'user_id',
                'multi_user_id',
                'mobile'
            )->from('storage as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->with(['storageShelfList' => function ($query) {
                $query->select(
                    'id',
                    'sort',
                    'remark',
                    'shelf_name',
                    'storage_id',
                    'shelf_type',
                    'id as shelf_id',
                    'is_product_shelf',
                )->with('locationList', function ($query) {
                    $query->select(
                        'sort',
                        'remark',
                        'shelf_id',
                        'location_name',
                        'location_type',
                        'id as location_id',
                        'is_product_shelf_location',
                        'standard_num',
                    )->where('status', 1)->orderBy('sort', 'asc')
                        ->orderBy('location_type', 'asc');
                })->where('status', 1)->orderBy('sort', 'asc')
                    ->orderBy('shelf_type', 'asc');
            }])->where(function ($query) use ($condition, $storageIdArr) {
                $query->where('a.delete_flag', 0);
                if (!empty($condition)) {
                    $query->where($condition);
                } else {
                    $query->whereIn('a.id', $storageIdArr);
                }
            })->orderBy('a.created_at', 'desc')
            //->paginate($data['pageSize'], ['*'], '', $data['currentPage'])->toArray();
            ->get()->toArray();
        if (!empty($list)) {
            foreach ($list as &$val) {
                $val['shelf_num'] = 0;
                $val['storage_location_list'] = [];
                if (!empty($val['storage_shelf_list'])) {
                    $val['shelf_num'] = count($val['storage_shelf_list']);
                    foreach ($val['storage_shelf_list'] as &$sVal) {
                        $sVal['location_num'] = 0;
                        if (!empty($sVal['location_list'])) {
                            $sVal['location_num'] = count($sVal['location_list']);
                            foreach ($sVal['location_list'] as $lVal) {
                                $val['storage_location_list'][] = $lVal;
                            }
                        }
                    }
                }
            }
            $val['staff_list'] = [];
            if (!empty($val['multi_user_id'])) {
                $userIds = array_filter(explode(
                    ',',
                    $val['multi_user_id']),
                    function ($v) {
                        return $v !== '';
                    });
                $userList = AdminModel::select(
                    'id',
                    'nickname',
                    'username',
                    'position',
                    'mobile'
                )->whereIn('id', $userIds)->get();
                if (!empty($userList)) {
                    $userList = $userList->toArray();
                    foreach ($userList as &$uVal) {
                        $uVal['storage_name'] = $val['storage_name'];
                    }
                }
                $val['staff_list'] = !empty($userList) ? $userList : [];
            }
        }
        return $list;
    }

    public static function newTwoList(array $data, array $condition, array $storageIdArr): array
    {
        $list = StorageModel::query()
            ->select(
                'a.id',
                'a.id as storage_id',
                'storage_name',
                'storage_address',
                'a.remarks',
                'username',
                'nickname',
                'user_id',
                'multi_user_id',
                'mobile'
            )->from('storage as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->with(['storageShelfList' => function ($query) use ($data) {
                $query->select(
                    'id',
                    'sort',
                    'tag_id',
                    'volume',
                    'remark',
                    'shelf_name',
                    'storage_id',
                    'shelf_type',
                    'id as shelf_id',
                    'is_product_shelf',
                )->where('status', 1)
                    ->where(function ($query) use ($data) {
                        if (!empty($data['tag_id']))
                            $query->where('tag_id', $data['tag_id']);
                    })
                    ->orderBy('sort', 'asc')
                    ->orderBy('shelf_type', 'asc');
            }])->where(function ($query) use ($condition, $storageIdArr) {
                $query->where('a.delete_flag', 0);
                if (!empty($condition)) {
                    $query->where($condition);
                } else {
                    $query->whereIn('a.id', $storageIdArr);
                }
            })->orderBy('a.created_at', 'desc')
            ->get()->toArray();
        if (!empty($list)) {
            foreach ($list as &$val) {
                $shelfIdArr = StorageShelfModel::query()
                    ->where([
                        'status' => 1,
                        'storage_id' => $val['id'],
                    ])->pluck('id')->toArray();
                $val['total_shelf_num'] = count($shelfIdArr);
                $locationIdArr = StorageShelfLocationModel::query()
                    ->where([
                        'status' => 1,
                        'storage_id' => $val['id'],
                    ])->whereIn('shelf_id', $shelfIdArr)->pluck('id')->toArray();
                $val['total_location_num'] = count($locationIdArr);
                $animalNum = 0;
                if (!empty($locationIdArr)) {
                    $animalNum = LocationAnimalModel::query()
                        ->where([
                            'delete_flag' => 0,
                            'type' => 0
                        ])->whereIn('location_id', $locationIdArr)->sum('num');
                }
                $val['total_storage_num'] = (int)$animalNum;
                $val['tag_list'] = [];
                $tagList = ShelfLocationTagModel::query()
                    ->select('id', 'tag_name', 'color')
                    ->where([
                        'type' => 0,
                    ])->orderBy('sort', 'desc')
                    ->orderBy('id', 'desc')
                    ->get()->toArray();
                if (!empty($tagList)) {
                    foreach ($tagList as &$tVal) {
                        $tVal['shelf_num'] = StorageShelfModel::query()
                            ->where([
                                'status' => 1,
                                'storage_id' => $val['id']
                            ])->whereIn('tag_id', [$tVal['id'], 0])->count();
                        if ($tVal['id'] !== 3) {
                            $tVal['shelf_num'] = StorageShelfModel::query()
                                ->where([
                                    'status' => 1,
                                    'tag_id' => $tVal['id'],
                                    'storage_id' => $val['id']
                                ])->count();
                        }
                    }
                    $val['tag_list'] = $tagList;
                }

                if (!empty($val['storage_shelf_list'])) {
                    foreach ($val['storage_shelf_list'] as &$sVal) {
                        $locationList = StorageShelfLocationModel::query()
                            ->where([
                                'status' => 1,
                                'shelf_id' => $sVal['id'],
                                'storage_id' => $sVal['storage_id'],
                            ])->get();
                        $sVal['location_num'] = 0;
                        $sVal['location_animal_num'] = 0;
                        if (!empty($locationList->toArray())) {
                            $locationList = $locationList->toArray();
                            $sVal['location_num'] = count($locationList);
                            $locIds = array_column($locationList, 'id');
                            $sVal['location_animal_num'] = LocationAnimalModel::query()
                                ->where([
                                    'delete_flag' => 0,
                                    'type' => 0,
                                ])
                                ->whereIn('location_id', $locIds)
                                ->sum('num');
                        }
                        $sVal['color'] = '#6e7781';
                        if (!empty($sVal['tag_id'])) {
                            $sVal['color'] = ShelfLocationTagModel::query()
                                ->where('id', $sVal['tag_id'])->value('color');
                        }
                    }
                }
            }
            $val['staff_list'] = [];
            if (!empty($val['multi_user_id'])) {
                $userIds = array_filter(explode(
                    ',',
                    $val['multi_user_id']),
                    function ($v) {
                        return $v !== '';
                    });
                $userList = AdminModel::select(
                    'id',
                    'nickname',
                    'username',
                    'position',
                    'mobile'
                )->whereIn('id', $userIds)->get();
                if (!empty($userList)) {
                    $userList = $userList->toArray();
                    foreach ($userList as &$uVal) {
                        $uVal['storage_name'] = $val['storage_name'];
                    }
                }
                $val['staff_list'] = !empty($userList) ? $userList : [];
            }
        }
        return $list;
    }

    public static function getShelfLocaList($data)
    {
        $info = StorageShelfModel::query()
            ->select('id', 'shelf_name', 'storage_id')
            ->where([
                'id' => $data['id'],
                'main_id' => $data['main_id']
            ])->first();
        if (!empty($info)) {
            $locModel = StorageShelfLocationModel::query()
                ->where([
                    'shelf_id' => $info['id'],
                    'main_id' => $data['main_id'],
                    'storage_id' => $info['storage_id'],
                    'status' => 1,
                ]);
            $stoManModel = StorageManageModel::query()
                ->where([
                    'shelf_id' => $info['id'],
                    'main_id' => $data['main_id'],
                    'storage_id' => $info['storage_id']
                ]);
            $info['total_locaiton_num'] = $locModel->count();
            $info['total_storage_num'] = (int)$stoManModel->sum('in_storage_num');
            $tagList = ShelfLocationTagModel::query()
                ->select('id', 'tag_name', 'color')
                ->where([
                    'type' => 1,
                ])->orderBy('sort', 'desc')
                //->orderBy('id', 'desc')
                ->get()->toArray();
            $list = $locModel->get()->toArray();

            $headTagList = [];
            if (!empty($tagList)) {
                foreach ($tagList as $key => &$tVal) {
                    $tVal['total_num'] = 0;
                    if (!empty($list)) {
                        $locaArr = [];
                        foreach ($list as &$val) {
                            if ($tVal['id'] === $val['tag_id']) {
                                $tVal['total_num'] += 1;
                                $locaArr[] = $val['id'];
                            }
                        }
                    }
                    if ($tVal['tag_name'] !== '空闲') {
                        $totalNum = 0;
                        $headTagList[$key]['id'] = $tVal['id'];
                        if (!empty($locaArr)) {
                            $totalNum = LocationAnimalModel::query()
                                ->where([
                                    'main_id' => $data['main_id'],
                                    'type' => 0
                                ])->whereIn('location_id', array_unique($locaArr))
                                ->sum('num');
                        }
                        $headTagList[$key]['head_tag_name'] = $tVal['tag_name'] . '数：' . (int)$totalNum;
                    }
                }
            }
            if (!empty($data['tag_id'])) {
                $locModel->where('tag_id', $data['tag_id']);
            }
            $list = $locModel->orderBy('sort', 'asc')->get()->toArray();
            if (!empty($list)) {
                foreach ($list as &$val) {
                    $animalInfo = LocationAnimalModel::where([
                        'main_id' => $data['main_id'],
                        'location_id' => $val['id'],
                        'delete_flag' => 0,
                        'type' => 0,
                    ])->first();
                    $sum = 0;
                    $goodsList = [];
                    if (!empty($animalInfo)) {
                        $goodsList[] = $animalInfo;
                        $sum = $animalInfo['num'];
                    }
                    $val['animal_info'] = $goodsList;
                    $val['location_storage_num'] = $sum;
                    $val['color'] = '#6e7781';
                    if (!empty($val['tag_id'])) {
                        $val['color'] = ShelfLocationTagModel::query()
                            ->where('id', $val['tag_id'])->value('color');
                    }
                    if (empty($val['log_no'])) {
                        $val['log_no'] = getNO('storage_shelf_location', 'log_no');
                        StorageShelfLocationModel::query()
                            ->where('id', $val['id'])
                            ->update(['log_no' => $val['log_no']]);
                    }
                    $logList = LocationLogModel::query()
                        ->where([
                            'location_id' => $val['id'],
                            'type' => 0,
                            'delete_flag' => 0,
                            'log_no' => $val['log_no']
                        ])->orderBy('created_at', 'desc')->limit(3)->get();
                    if (!empty($logList->toArray())) {
                        $logList = $logList->toArray();
                        foreach ($logList as &$lVal) {
                            if (!empty($lVal['conent4'])) {
                                if (is_numeric((int)$lVal['conent4'])) {
                                    $lVal['conent4'] = ShelfLocationTagModel::query()
                                        ->where([
                                            'id' => $lVal['conent4']
                                        ])->value('tag_name') ?? $lVal['conent4'];
                                }
                            }
                            $arr = ['conent1', 'conent2', 'conent3', 'conent4'];
                            foreach ($arr as $v) {
                                if ($lVal[$v] === null) $lVal[$v] = '';
                            }
                            $lVal['animal_img'] = '';
                            $lVal['in_price'] = 0;
                            $lVal['sell_price'] = 0;
                            if (!empty($lVal['animal_id'])) {
                                $animalInfo = LocationAnimalModel::query()
                                    ->where([
                                        'id' => $lVal['animal_id']
                                    ])->first();
                                if (!empty($animalInfo)) {
                                    $lVal['animal_img'] = $animalInfo['animal_img'] ?? '';
                                    $lVal['in_price'] = (float)$animalInfo['in_price'];
                                    $lVal['sell_price'] = (float)$animalInfo['sell_price'];
                                }
                            }
                            $lVal['tag_content'] = '';
                            if (!empty($lVal['out_tag_id'])) {
                                $lVal['tag_content'] = OutAnimalTagModel::query()
                                    ->where('id', $lVal['out_tag_id'])
                                    ->value('tag_content') ?? '';
                            }
                        }
                    } else {
                        $logList = [];
                    }
                    $val['new_log_info'] = $logList;
                }
            }
            $info['head_tag_list'] = array_values($headTagList);
            $info['tag_list'] = $tagList;
            $info['location_list'] = $list;
        }
        return $info;
    }

    public static function getNoTokenShelfLocaList($data)
    {
        $info = StorageShelfModel::query()
            ->select('id', 'shelf_name', 'storage_id')
            ->where([
                'id' => $data['shelfId'],
            ])->first();
        if (!empty($info)) {
            $locModel = StorageShelfLocationModel::query()
                ->where([
                    'shelf_id' => $info['id'],
                    'main_id' => $info['main_id'],
                    'storage_id' => $info['storage_id'],
                    'status' => 1,
                ]);

            $stoManModel = StorageManageModel::query()
                ->where([
                    'shelf_id' => $info['id'],
                    'main_id' => $info['main_id'],
                    'storage_id' => $info['storage_id']
                ]);
            $info['total_locaiton_num'] = $locModel->count();
            $info['total_storage_num'] = (int)$stoManModel->sum('in_storage_num');
            $tagList = ShelfLocationTagModel::query()
                ->select('id', 'tag_name', 'color')
                ->where([
                    'type' => 1,
                ])->orderBy('sort', 'desc')
                ->get()->toArray();
            $list = $locModel->get()->toArray();
            $headTagList = [];
            if (!empty($tagList)) {
                foreach ($tagList as $key => &$tVal) {
                    $tVal['total_num'] = 0;
                    if (!empty($list)) {
                        $locaArr = [];
                        foreach ($list as &$val) {
                            if ($tVal['id'] === $val['tag_id']) {
                                $tVal['total_num'] += 1;
                                $locaArr[] = $val['id'];
                            }
                        }
                    }
                    if ($tVal['tag_name'] !== '空闲') {
                        $totalNum = 0;
                        $headTagList[$key]['id'] = $tVal['id'];
                        if (!empty($locaArr)) {
                            $totalNum = LocationAnimalModel::query()
                                ->where([
                                    'main_id' => $info['main_id'],
                                    'type' => 0
                                ])->whereIn('location_id', $locaArr)
                                ->sum('num');
                        }
                        $headTagList[$key]['head_tag_name'] = $tVal['tag_name'] . '数：' . (int)$totalNum;
                    }
                }
            }
            if (!empty($data['tag_id'])) {
                $locModel->where('tag_id', $data['tag_id']);
            }
            $list = $locModel->orderBy('sort', 'asc')->get()->toArray();
            if (!empty($list)) {
                foreach ($list as &$val) {
                    $animalInfo = LocationAnimalModel::where([
                        'main_id' => $info['main_id'],
                        'location_id' => $val['id'],
                        'delete_flag' => 0,
                        'type' => 0,
                    ])->first();
                    $sum = 0;
                    $goodsList = [];
                    if (!empty($animalInfo)) {
                        $goodsList[] = $animalInfo;
                        $sum = $animalInfo['num'];
                    }
                    $val['animal_info'] = $goodsList;
                    $val['location_storage_num'] = $sum;
                    $val['color'] = '#6e7781';
                    if (!empty($val['tag_id'])) {
                        $val['color'] = ShelfLocationTagModel::query()
                            ->where('id', $val['tag_id'])->value('color');
                    }
                    if (empty($val['log_no'])) {
                        $val['log_no'] = getNO('storage_shelf_location', 'log_no');
                        StorageShelfLocationModel::query()
                            ->where('id', $val['id'])
                            ->update(['log_no' => $val['log_no']]);
                    }
                    $logList = LocationLogModel::query()
                        ->where([
                            'location_id' => $val['id'],
                            'type' => 0,
                            'delete_flag' => 0
                        ])->orderBy('created_at', 'desc')->limit(3)->get();
                    if (!empty($logList->toArray())) {
                        $logList = $logList->toArray();
                        foreach ($logList as &$lVal) {
                            if (!empty($lVal['conent4'])) {
                                if (is_numeric((int)$lVal['conent4'])) {
                                    $lVal['conent4'] = ShelfLocationTagModel::query()
                                        ->where([
                                            'id' => $lVal['conent4']
                                        ])->value('tag_name') ?? $lVal['conent4'];
                                }
                            }
                            $arr = ['conent1', 'conent2', 'conent3', 'conent4'];
                            foreach ($arr as $v) {
                                if ($lVal[$v] === null) $lVal[$v] = '';
                            }
                            $lVal['animal_img'] = '';
                            $lVal['in_price'] = 0;
                            $lVal['sell_price'] = 0;
                            if (!empty($lVal['animal_id'])) {
                                $animalInfo = LocationAnimalModel::query()
                                    ->where([
                                        'id' => $lVal['animal_id']
                                    ])->first();
                                if (!empty($animalInfo)) {
                                    $lVal['animal_img'] = $animalInfo['animal_img'] ?? '';
                                    $lVal['in_price'] = (float)$animalInfo['in_price'];
                                    $lVal['sell_price'] = (float)$animalInfo['sell_price'];
                                }
                            }
                        }
                    } else {
                        $logList = [];
                    }
                    $val['new_log_info'] = $logList;
                }
            }
            $info['head_tag_list'] = array_values($headTagList);
            $info['tag_list'] = $tagList;
            $info['location_list'] = $list;
        }
        return $info;
    }

    /**
     *仓库、货架、库位的批量删除
     * Author: zlf
     * Created at 2024/8/27 10:59
     * @param $data
     * @return JsonResponse|null
     */
    public static function batchDel($data): ?JsonResponse
    {
        DB::beginTransaction();
        try {
            $locaIdArr = [];
            if (!empty($data['storage_ids'])) {
                $storIdArr = explode(',', $data['storage_ids']);
                StorageModel::query()
                    ->where('main_id', $data['main_id'])
                    ->whereIn('id', $storIdArr)->update(['delete_flag' => 1]);
                StorageShelfModel::query()
                    ->where('main_id', $data['main_id'])
                    ->whereIn('storage_id', $storIdArr)->update(['status' => 0]);
                $locaIdArr = StorageShelfLocationModel::query()
                    ->where('main_id', $data['main_id'])
                    ->whereIn('storage_id', $storIdArr)
                    ->pluck('id')->toArray();
                StorageShelfLocationModel::query()
                    ->where('main_id', $data['main_id'])
                    ->whereIn('storage_id', $storIdArr)->update(['status' => 0]);
            }
            if (!empty($data['shelf_ids'])) {
                $shelfIdArr = explode(',', $data['shelf_ids']);
                StorageShelfModel::query()
                    ->where('main_id', $data['main_id'])
                    ->whereIn('id', $shelfIdArr)->update(['status' => 0]);
                $locaIdArr = StorageShelfLocationModel::query()
                    ->where('main_id', $data['main_id'])
                    ->whereIn('shelf_id', $shelfIdArr)->pluck('id')
                    ->toArray();
                StorageShelfLocationModel::query()
                    ->where('main_id', $data['main_id'])
                    ->whereIn('shelf_id', $shelfIdArr)->update(['status' => 0]);
            }

            if (!empty($data['loca_ids'])) {
                $locaIdArr = explode(',', $data['loca_ids']);
                StorageShelfLocationModel::query()
                    ->where('main_id', $data['main_id'])
                    ->whereIn('id', $locaIdArr)->update(['status' => 0]);
            }
            if (!empty($locaIdArr)) {
                LocationAnimalModel::query()->where('main_id', $data['main_id'])
                    ->whereIn('location_id', $locaIdArr)->update(['delete_flag' => 1]);
            }
            CommonService::operateResult($data['user_id'], $data['time'], $data, '批量删除成功！');
            DB::commit();
            return success();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('仓库、货架、库位的批量删除异常：' . var_export($e->getMessage(), 'true'));
            return fail('', $e->getMessage());
        }

    }

    public static function updShelf($data)
    {
        $model = StorageShelfModel::query()
            ->where([
                'status' => 1,
                'id' => $data['shelfId'],
                'main_id' => $data['main_id'],
            ]);
        DB::beginTransaction();
        try {
            if (!empty($info = $model->first())) {

                if (StorageShelfModel::query()
                    ->where([
                        'status' => 1,
                        ['id', '!=', $info['id']],
                        'main_id' => $data['main_id'],
                        'shelf_name' => $data['shelfName'],
                        'storage_id' => $info['storage_id'],
                    ])->exists()) {
                    throw new \RuntimeException('库位名称，不可重复！');
                }
                CommonService::operateResult($data['user_id'], $data['time'], $data, '编辑成功');
                $data['shelf_name'] = $data['shelfName'];
                unset($data['time'], $data['shelfId'], $data['shelfName'], $data['user_id']);

                $bool = $model->update($data);
                if (!$bool)
                    throw new \RuntimeException('编辑失败');
            } else {
                throw new \RuntimeException('没有找到，修改信息！');
            }
            DB::commit();
            return success();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('修改货架异常：' . var_export($e->getMessage(), true));
            return fail('', $e->getMessage());
        }
    }

    public static function updLocation($data)
    {
        DB::beginTransaction();
        try {
            if (!empty($data['locationId'])) {
                if (isset($data['locationName'])) {
                    if (empty($data['locationName'])) {
                        throw new \Exception('宠物名称，不能为空');
                    }
                }
                $idArr = explode(',', $data['locationId']);
                foreach ($idArr as $val) {
                    $locaInfo = StorageShelfLocationModel::query()->where([
                        'main_id' => $data['main_id'],
                        'id' => $val,
                        'status' => 1
                    ])->first();
                    if (empty($locaInfo))
                        throw new \RuntimeException('盒子数据异常！');

                    if (StorageShelfLocationModel::query()
                        ->where([
                            'main_id' => $data['main_id'],
                            'storage_id' => $locaInfo['storage_id'],
                            'status' => 1,
                            'location_name' => $data['locationName'],
                            ['id', '!=', $locaInfo['id']]
                        ])->exists()) {
                        throw new \RuntimeException('同仓库下盒子' . $data['locationName'] . '，名称不能重复');
                    }
                    $data['location_name'] = $data['locationName'];
                    unset($data['time'], $data['user_id'], $data['locationId'], $data['locationName']);
                    $bool = StorageShelfLocationModel::query()
                        ->where('id', $locaInfo['id'])
                        ->update($data);
                    if (!$bool) {
                        throw new \RuntimeException('编辑失败');
                    }
                }
                DB::commit();
                return success();
            } else {
                throw new \Exception('请选择盒子！');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('修改盒子异常' . var_export($e->getMessage(), true));
            return fail('', $e->getMessage());
        }
    }

    public
    static function batchUpdShelfStatus($data): ?JsonResponse
    {
        if (!empty($data['shelf_ids'])) {
            $shelfIdArr = explode(',', $data['shelf_ids']);
            $bool = StorageShelfModel::query()
                ->where('main_id', $data['main_id'])
                ->whereIn('id', $shelfIdArr)
                ->update(['tag_id' => $data['id']]);
            if ($bool) {
                CommonService::operateResult($data['user_id'], $data['time'], $data, '状态修改成功');
                return success();
            } else
                return fail('', '修改失败');
        }
        if (!empty($data['location_ids'])) {
            $locationIdArr = explode(',', $data['location_ids']);
            $bool = StorageShelfLocationModel::query()
                ->where('main_id', $data['main_id'])
                ->whereIn('id', $locationIdArr)
                ->update(['tag_id' => $data['id']]);
            if ($bool) {
                CommonService::operateResult($data['user_id'], $data['time'], $data, '状态修改成功');
                return success();
            } else
                return fail('', '修改失败');
        }
        if (empty($data['shelf_ids']) && empty($data['location_ids'])) {
            return fail('', '请选择修改记录！');
        }
    }

    public
    static function getCustomTagList($data)
    {
        return CustomTagModel::select(
            'id',
            'label_name',
            'color',
            'is_top',
            'use_type'
        )
            ->where($data)
            ->where([
                'delete_flag' => 0,
                'use_type' => 1
            ])
            ->orderBy('is_top', 'DESC')
            ->orderBy('sort_number', 'DESC')
            ->orderBy('create_time', 'ASC')
            ->get();
    }

    public static function outInGoodsList($data)
    {
        $list = '';
        $locaIdArr = explode(',', $data['location_ids']);
        if ($data['req_type'] == 1) {//出库
            $manageList = StorageManageModel::query()
                ->select(
                    'a.id',
                    'a.materiel_mean_cost as cost',
                    'a.storage_id',
                    'b.storage_name',
                    'b.storage_address',
                    'a.in_storage_num',
                    'a.alert_num',
                    'a.virtual_storage_num',
                    'a.shelf_id',
                    'a.location_id',
                    'c.shelf_name',
                    'd.location_name',
                    'a.sort_flag',
                    'time_warning_flag',
                    'e.id as type_id',
                    'e.materiel_name',
                    'e.type_name',
                    'e.materiel_img',
                    'e.materiel_no',
                    'e.cost',
                    'g.id as f_class_id',
                    'g.class_name as f_class_name',
                    'g.class_no as f_class_no',
                    'f.id as s_class_id',
                    'f.class_name as s_class_name',
                    'f.class_no as s_class_no',
                    'e.is_product_materiel',
                    'e.selling_price',
                    'e.lower_selling_price',
                    'e.remark',
                    'e.is_use_serial',
                    'e.materiel_unit',
                    'e.is_product_materiel',
                )->from('storage_manage as a')
                ->leftJoin('storage as b', 'b.id', '=', 'a.storage_id')
                ->leftJoin('storage_shelf as c', 'c.id', '=', 'a.shelf_id')
                ->leftJoin('storage_shelf_location as d', 'd.id', '=', 'a.location_id')
                ->leftJoin('materiel_type as e', 'e.id', '=', 'a.type_id')
                ->leftJoin('materiel_class as f', 'e.materiel_class_id', '=', 'f.id')
                ->leftJoin('materiel_class as g', 'g.id', '=', 'f.parent_id')
                ->where([
                    'a.main_id' => $data['main_id'],
                    'a.delete_flag' => 0,
                    'b.delete_flag' => 0,
                    'c.status' => 1,
                    'd.status' => 1,
                    'e.delete_flag' => 0,
                    'f.delete_flag' => 0,
                    'g.delete_flag' => 0,
                    ['in_storage_num', '>', 0]
                ])->whereIn('a.location_id', $locaIdArr)
                ->orderBy('in_storage_num', 'desc')->get();
            if (!empty($manageList->toArray())) {
                $list = $manageList->toArray();
                foreach ($list as &$value) {
                    if (!empty($value['materiel_img'])) {
                        if (strpos($value['materiel_img'], ',') !== false) {
                            $materielImg = explode(',', $value['materiel_img']);
                            if (empty($materielImg[0])) $materielImg[0] = $materielImg[1];
                            $value['materiel_img'] = $materielImg[0];
                        }
                    }
                }
            }
        } else {//入库
            $goodslist = StorageManageModel::query()
                ->select(
                    'b.id',
                    'b.id as type_id',
                    'b.materiel_name',
                    'b.type_name',
                    'b.materiel_img',
                    'b.materiel_no',
                    'b.cost',
                    'd.id as f_class_id',
                    'd.class_name as f_class_name',
                    'd.class_no as f_class_no',
                    'c.id as s_class_id',
                    'c.class_name as s_class_name',
                    'c.class_no as s_class_no',
                    'b.is_product_materiel',
                    'b.selling_price',
                    'b.lower_selling_price',
                    'b.remark',
                    'b.is_use_serial',
                    'b.materiel_unit',
                    'b.is_product_materiel',
                )->from('storage_manage as a')
                ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
                ->leftJoin('materiel_class as c', 'b.materiel_class_id', '=', 'c.id')
                ->leftJoin('materiel_class as d', 'd.id', '=', 'c.parent_id')
                ->where([
                    'b.delete_flag' => 0,
                    'a.main_id' => $data['main_id'],
                ])->whereIn('a.location_id', $locaIdArr)->get();
            if (!empty($goodslist->toArray())) {
                $list = $goodslist->toArray();
                foreach ($list as &$value) {
                    if (!empty($value['materiel_img'])) {
                        if (strpos($value['materiel_img'], ',') !== false) {
                            $materielImg = explode(',', $value['materiel_img']);
                            if (empty($materielImg[0])) $materielImg[0] = $materielImg[1];
                            $value['materiel_img'] = $materielImg[0];
                        }
                    }
                }
            }
        }
        return $list;
    }

    public static function transferShelf($data): ?JsonResponse
    {
        $locaIdArr = [];
        if (!empty($data['location_ids'])) {
            $locaIdArr = explode(',', $data['location_ids']);
        } else {
            return fail('', '请选择要转移的库位');
        }
        if (!empty($data['target_shelf_id'])) {
            $model = StorageShelfLocationModel::query()
                ->where([
                    'main_id' => $data['main_id'],
                    'status' => 1,
                ])->whereIn('id', $locaIdArr);
            DB::beginTransaction();
            try {
                $locaitonList = $model->get()->toArray();
                if (!empty($locaitonList)) {
                    $shelfIdArr = array_column($locaitonList, 'shelf_id');
                    /* if (in_array($data['target_shelf_id'], $shelfIdArr, true)) {
                         return fail('', '同库位不能转移！');
                     }*/
                    $logData = [];
                    $tarShelfName = StorageShelfModel::query()
                        ->where('id', $data['target_shelf_id'])
                        ->value('shelf_name');
                    foreach ($locaitonList as $sVal) {
                        /*    if (StorageShelfLocationModel::query()->where([
                                'main_id' => $data['main_id'],
                                'status' => 1,
                                'shelf_id' => $data['target_shelf_id'],
                                'location_name' => $sVal['location_name'],
                            ])->exists()) {
                                return fail('', '目标货架下，库位名称：' . $sVal['location_name'] . '已存在！');
                            }*/
                        $shelfName = StorageShelfModel::query()
                            ->where('id', $sVal['shelf_id'])
                            ->value('shelf_name');
                        $logData[] = [
                            'log_no' => $sVal['log_no'],
                            'conent1' => $shelfName,
                            'conent2' => $sVal['location_name'],
                            'conent3' => '转移',
                            'conent4' => $tarShelfName . '-' . $sVal['location_name'],
                            'main_id' => $data['main_id'],
                            'user_id' => $data['user_id'],
                            'location_id' => $sVal['id'],
                            'add_type' => 1,
                            'in_out_type' => 2,
                            'type' => 0,
                            'remark' => $data['remark'] ?? '',
                            'out_tag_id' => $data['out_tag_id'] ?? 0,
                        ];
                    }
                    LocationLogModel::query()->insert($logData);
                }
                $model->update(['shelf_id' => $data['target_shelf_id']]);
                StorageManageModel::query()->where([
                    'main_id' => $data['main_id'],
                    'delete_flag' => 0,
                ])->where('location_id', $locaIdArr)->update(['shelf_id' => $data['target_shelf_id']]);
                CommonService::operateResult($data['user_id'], $data['time'], $data, '转移成功');
                DB::commit();
                return success();
            } catch (\Exception $e) {
                DB::rollBack();
                Log::debug('转移的库位异常：' . var_export($e->getMessage(), true));
                return fail('', $e->getMessage());
            }
        } else {
            return fail('', '请选择目标的货架！');
        }
    }

    public static function getIndex($data)
    {
        $info = [];
        $locaInfo = StorageShelfLocationModel::query()
            ->select('id', 'tag_id')
            ->where([
                'status' => 1,
                'main_id' => $data['main_id'],
                'storage_id' => $data['storage_id']
            ])->get()->toArray() ?? [];
        $shelfList = StorageShelfModel::query()
            ->select('*',
                'id as shelf_id'
            )->where([
                'status' => 1,
                'main_id' => $data['main_id'],
                'storage_id' => $data['storage_id']
            ])->get()->toArray() ?? [];

        if (!empty($locaInfo)) {
            $locaIdArr = array_column($locaInfo, 'id');
            $list = LocationLogModel::query()
                ->select(
                    'b.id',
                    'num',
                    'animal_id',
                    'in_price',
                    'sell_price',
                    'in_out_type',
                    'a.log_no as l_log_no',
                    'b.log_no as a_log_no',
                    'a.location_id',
                )->from('location_log as a')
                ->leftJoin('location_animal as b', 'b.log_no', '=', 'a.log_no')
                ->where([
                    'a.delete_flag' => 0,
                    'b.delete_flag' => 0,
                    'a.main_id' => $data['main_id'],
                ])->whereIn('in_out_type', [1, 3])
                ->whereIn('a.location_id', $locaIdArr)
                ->where(function ($query) use ($data) {
                    $startTime = now()->startOfDay()->format('Y-m-d H:i:s');
                    $endTime = now()->endOfDay()->format('Y-m-d H:i:s');
                    if (!empty($data['date'])) {
                        $startTime = Carbon::parse($data['date'])->startOfDay()->format('Y-m-d H:i:s');
                        $endTime = Carbon::parse($data['date'])->endOfDay()->format('Y-m-d H:i:s');
                        $query->whereBetween('a.created_at', [$startTime, $endTime]);
                    }
                })->get()->toArray() ?? [];
            $info['die_num'] = 0;
            $info['err_num'] = 0;
            $info['flaw_num'] = 0;
            $info['else_num'] = 0;
            $info['health_num'] = 0;
            $info['illness_num'] = 0;
            $info['in_total_num'] = 0;
            $info['out_total_num'] = 0;
            $info['in_total_price'] = 0;
            $info['out_total_price'] = 0;
            $info['paid_total_price'] = 0;
            if (!empty($list)) {
                foreach ($list as $val) {
                    if ($val['in_out_type'] === 1) {
                        //$info['in_total_num'] += $val['num'];
                        $info['in_total_price'] += $val['in_price'];
                    } else {
                        //$info['out_total_num'] += $val['num'];
                        $info['out_total_price'] += $val['sell_price'];
                    }
                }
            }
            foreach ($locaInfo as $lVal) {
                $model = LocationAnimalModel::query()
                    ->where([
                        'type' => 0,
                        'delete_flag' => 0,
                        'main_id' => $data['main_id'],
                    ])->where('location_id', $lVal['id']);
                if (in_array($lVal['tag_id'], [6, 11, 12, 13], true)) {
                    $info['illness_num'] += $model->sum('num') ?? 0;
                }
                if ($lVal['tag_id'] === 4) {
                    $info['health_num'] += $model->sum('num') ?? 0;;
                }
                if ($lVal['tag_id'] === 7) {
                    $info['flaw_num'] += $model->sum('num') ?? 0;;
                }
                if ($lVal['tag_id'] === 10) {
                    $info['else_num'] += $model->sum('num') ?? 0;;
                }
            }
        }
        $info['tag_list'] = [];
        $tagList = ShelfLocationTagModel::query()
            ->select('id', 'tag_name', 'color')
            ->where([
                'type' => 0,
            ])->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->get()->toArray();
        if (!empty($tagList)) {
            foreach ($tagList as &$tVal) {
                $tVal['shelf_num'] = StorageShelfModel::query()
                    ->where([
                        'status' => 1,
                        'storage_id' => $data['storage_id']
                    ])->whereIn('tag_id', [$tVal['id'], 0])->count();
                if ($tVal['id'] !== 3) {
                    $tVal['shelf_num'] = StorageShelfModel::query()
                        ->where([
                            'status' => 1,
                            'tag_id' => $tVal['id'],
                            'storage_id' => $data['storage_id']
                        ])->count();
                }
            }
            $info['tag_list'] = $tagList;
        }
        if (!empty($shelfList)) {
            foreach ($shelfList as &$sVal) {
                $sVal['location_num'] = StorageShelfLocationModel::query()
                    ->where([
                        'status' => 1,
                        'shelf_id' => $sVal['shelf_id'],
                        'storage_id' => $data['storage_id'],
                    ])->count();
                $sVal['color'] = '#6e7781';
                if (!empty($sVal['tag_id'])) {
                    $sVal['color'] = ShelfLocationTagModel::query()
                        ->where('id', $sVal['tag_id'])->value('color');
                }

            }
        }
        $info['shelf_list'] = $shelfList;
        return $info;
    }
}
